<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="add">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList" sort-orders="descending">
          <el-table-column label="序号" width="50px" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" class="Photo"> -->
              <ErrImg :src="scope.row.staffPhoto" class="Photo" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template v-slot="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="转正时间" sortable prop="correctionTime">
            <template v-slot="scope">
              {{ scope.row.correctionTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="LookEmployee(scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assigningRolesFn(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <el-dialog
          title="提示"
          :visible.sync="showDialog"
          width="50%"
        >
          <!-- 组件 -->
          <emDialog v-if="showDialog" :hiretype="hireType" @queding="quedingFn" @close="closeFn" />
        </el-dialog>
        <!-- 分配角色 -->
        <el-dialog

          title="分配角色"
          :visible.sync="showRoles"
          width="50%"
        >
          <assignRole ref="rolesDia" :roles="roles" @quedingguanbi="quedingguanbi" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import Employees from '@/constant/employees'
import emDialog from './emDialog.vue'
import dayjs from 'dayjs'
import assignRole from './assignRole.vue'
export default {
  name: 'Employees',
  components: {
    emDialog,
    assignRole
  },
  // 过滤器
  filters: {
    formatDate(value) {
      // 格式化时间
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      hireType: Employees.hireType, // 枚举数组
      showDialog: false,
      showRoles: false, // 分配角色对话框显示隐藏
      roles: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      // 重新渲染
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      // 重新渲染
      this.getEmployeeList()
    },
    // 获得员工列表
    async  getEmployeeList() {
      const res = await getEmployeeList(this.query)
      console.log(res.data.rows)
      // 手写 枚举
      // res.data.rows.forEach(item => {
      //   this.hireType.forEach(data => {
      //     if (item.formOfEmployment === data.id || Number(item.formOfEmployment) === data.id) {
      //       item.formOfEmployment = data.value
      //     } else {
      //       item.formOfEmployment = '未知'
      //     }
      //   })
      // })
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    async  del(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message.info('已取消')
      const res = await delEmployee(id)
      console.log(res)
      this.$message.success(res.message)
      this.getEmployeeList()
    },
    add() {
      this.showDialog = true
    },
    closeFn() {
      this.showDialog = false
    },
    formatter(row, column, cellValue, index) {
      const obj = this.hireType.find(item => {
        return Number(cellValue) === item.id
      })

      return obj ? obj.value : '未知'
    },
    quedingFn() {
      this.showDialog = false
      // 重新渲染
      this.getEmployeeList()
    },
    // 导出
    async downloadExcel() {
      const res = await getEmployeeList(this.query)
      const rows = res.data.rows
      // 接受返回值
      const jieshou = this.transData(rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        const header = jieshou.header
        const data = jieshou.data
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 枚举导出数据
    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 英文的key
      const Ekeys = Object.keys(rows[0])
      const header = Ekeys.map(item => {
        return map[item]
      })
      const data = rows.map(data => {
        return Object.values(data)
      })
      return { header, data }
    },
    // 点击查看员工详情
    LookEmployee(id) {
      this.$router.push({ path: '/detail?id=' + id })
    },
    // 分配角色
    assigningRolesFn(id) {
      // 数据更新 打开对话框（打开了组件）异步代码
      this.showRoles = true
      this.roles = id
      // 等到组件打开 在获取 在使用组件的方法
      this.$nextTick(() => {
        this.$refs.rolesDia.getEmployeeInformation()
      })
    },
    quedingguanbi() {
      this.showRoles = false
    }

  }
}
</script>

<style lang="scss" scoped>
.Photo{
width: 100px;
height: 100px;
border-radius: 50%;
}
</style>
